package com.alog.yzd.jdbc.hm;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;

public class MyDataSource implements DataSource {
    private static final String MYSQL_USERNAME = "root";
    private static final String MYSQL_PASSWORD = "123456";
    private static final String MYSQL_URL= "jdbc:mysql://localhost:3306/mydb";
    private LinkedList<Connection> conns = new LinkedList<>();

    private static int initCount = 5;
    private static int maxCount = 10;
    int currentCounts = 0;

    public MyDataSource(){
        try {
            for(int i = 0; i < initCount; i++){
                conns.addLast(createConnection());
                currentCounts++;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Connection createConnection() throws SQLException {
        //return DriverManager.getConnection(MYSQL_URL, MYSQL_USERNAME, MYSQL_PASSWORD);

//        Connection conn = DriverManager.getConnection(MYSQL_URL, MYSQL_USERNAME, MYSQL_PASSWORD);
//        return new MyConnection(conn, this);

        MyConnectionHandler handler = new MyConnectionHandler(this);
        Connection wrapper = handler.bind(DriverManager.getConnection(MYSQL_URL, MYSQL_USERNAME, MYSQL_PASSWORD));
        return wrapper;
    }

    public Connection getConnection() throws SQLException {
        synchronized (conns){
            if(conns.size() > 0){
                return conns.removeFirst();
            }
            if(currentCounts < maxCount){
                conns.addLast(createConnection());
                currentCounts++;
                return conns.removeFirst();
            }
            throw new SQLException("pool is empty");
        }

    }

    public void free(Connection conn){
        conns.addLast(conn);
    }
    //=====================================================================================
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
